/* Copyright (c) 2011 Alexandre Défossez
 * This file is part of HINAPT.
 *
 * HINAPT is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * HINAPT is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with HINAPT.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef THQUEUE_HPP
#define THQUEUE_HPP

#include "_tracker.hpp"

#include <queue>
/*!
  \file ThQueue.hpp

*/

/*!
  Queue thread-safe et capable de se débarasser de ses éléments les plus anciens
  quand elle est pleine.
*/
template<typename T> class ThQueue
{
  public:
    /*!
      \param maxSize taille maximale, infinie si 0
    */
    ThQueue(size_t maxSize=0):maxSize(maxSize){};
    /*!
      Rajoute une valeur à la queue.
      \param[in] val valeur a ajouter sur la queue.
    */

    void push(T &val){
      sf::Lock _lock(lock);
      q.push(val);
      while(maxSize>0 && q.size()>maxSize){
        printf("DROPING FRAME\n");
        q.pop();
      }
    }


    /*!
      Récupère et supprime de la queue la valeur la plus ancienne.
      \param[out] ret valeur récupérée.
      \return true si un élément a été retourné, false si la queue était vide.
    */
    bool pop(T &ret){
      sf::Lock _lock(lock);
      if (q.size()){
        ret = q.front();
        q.pop();
        return true;
      }
      return false;
    }
    /*!
      Change la taille maximale
    */
    void setMaxSize(double maxsize){
      sf::Lock _lock(lock);
      maxSize = maxsize;
    }
  private:
    /*!
      Queue non thread-safe utilisée pour le stockage
    */
    std::queue<T> q;
    /*!
      Verrou utilisé pour rendre les opérations thread-safe
    */
    sf::Mutex lock;
    /*!
      Taille maximale de la queue, 0 = infini.
    */
    size_t maxSize;
};

#endif // THQUEUE_HPP
